package com.sgcc.pda.hzaidl.impl;

import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;

import com.sgcc.pda.hw.ReturnResult;
import com.sgcc.pda.hzaidl.IHZAidlCallback;
import com.sgcc.pda.hzaidl.entity.BluetoothConnectParam;

import com.sgcc.pda.hzaidl.entity.BluetoothDiscoveryParam;
import com.sgcc.pda.hzaidl.entity.ResponseBean;
import com.sgcc.pda.tools.JsonUtils;
import com.sgcc.pda.tools.LogPrintUtils;


import java.util.Set;

/**
 * @创建者：suven on 2019/12/17 12:28
 * @描述：
 * @版本：1.0
 * @修改人：
 * @修改时间：
 * @修改说明：
 * @修改版本：
 */
public class BackClipManager {
    private static BackClipManager mInstance;


    /**
     * 单例
     *
     * @return
     */
    public static synchronized BackClipManager getInstance() {
        if (mInstance == null) {
            mInstance = new BackClipManager();
        }
        return mInstance;
    }

    /**
     * 连接蓝牙
     * macAddress  背夹mac地址
     * backClipTimeOutClose  背夹超时关闭时间
     *
     * @return 成功返回 true，失败返回 false
     */
    public interface BtConnectCallBack {
        /**
         * 蓝牙连接成功失败的回调
         *
         * @param connStatus true：连接成功  false连接失败
         */
        void connect(boolean connStatus, int code, String msg);

        /**
         * 监听蓝牙断开的回调，若蓝牙断开会走这个监听
         */
        void disConnect();


    }

    public void btConnect(String macAddress, int backClipTimeOutClose, final BtConnectCallBack callBack) {
        final long startTime = System.currentTimeMillis();
        BluetoothConnectParam.Request param = new BluetoothConnectParam.Request(macAddress, backClipTimeOutClose);
        final String requestParams = JsonUtils.toJson(param);
        HardWareUtil.requestHardwareData(false, "backclip_bluetoothConnect", requestParams, new IHZAidlCallback.Stub() {
            @Override
            public void callback(String result) {
                ResponseBean responseBean = JsonUtils.toBean(result, ResponseBean.class);
                ReturnResult returnResult =JsonUtils.toBean(responseBean.getMsgJson(), ReturnResult.class);

                if (null == returnResult || null == returnResult.getDatas() || returnResult.getDatas().isEmpty()) {
                    onCallBack(null);
                    return;
                }
                BluetoothConnectParam.Response response = JsonUtils.toBean(returnResult.getDatas().get(0), BluetoothConnectParam.Response.class);
                if (null == response) {
                    onCallBack(null);
                    return;
                }
                onCallBack(response);

            }

            void onCallBack(final BluetoothConnectParam.Response response) {
                if (Looper.myLooper() == Looper.getMainLooper()) {
                    callback(response);
                    return;
                }
                Handler mainLooper = new Handler(Looper.getMainLooper());
                mainLooper.post(new Runnable() {
                    @Override
                    public void run() {
                        callback(response);
                    }
                });
            }


            private void callback(final BluetoothConnectParam.Response response) {
                if (null != callBack) {
                    if (null == response) {
                        callBack.connect(false, -1, "无响应数据");
                        return;
                    }
                    if (response.isDisConnect()) {
                        callBack.disConnect();
                    } else {
                        callBack.connect(response.isSuccess(), response.getCode(), response.getMsg());
                        LogPrintUtils.e("time", "蓝牙建立连接耗时：" + (System.currentTimeMillis() - startTime));
                    }
                }

            }
        });
    }

    /**
     * 蓝牙是否连接
     *
     * @return 成功返回 true，失败返回 false
     */
    public boolean btIsConnect() {
        ReturnResult returnResult = HardWareUtil.requestHardwareData(false, "backclip_bluetoothIsConnected", "");
        return returnResult != null && returnResult.getCode() == 0;
    }


    /**
     * 断开蓝牙连接
     *
     * @return 成功返回 true，失败返回 false
     */
    public boolean btDisConnect() {
        ReturnResult returnResult = HardWareUtil.requestHardwareData(false, "backclip_bluetoothDisConnect", "");
        return returnResult != null && returnResult.getCode() == 0;
    }

    /**
     * 断开蓝牙回调
     */
    public interface BtDisConnectCallBack {

        /**
         * 监听蓝牙断开的回调，若蓝牙断开会走这个监听
         */
        void disConnect();
    }

    /**
     * 监听蓝牙断开事件
     *
     * @return 成功返回 true，失败返回 false
     */
    public void registerBtDisConnect(final BtDisConnectCallBack callBack) {
        HardWareUtil.requestHardwareData(false, "backclip_bluetoothDisConnectState", "", new IHZAidlCallback.Stub() {
            @Override
            public void callback(String result) {
                ResponseBean responseBean = JsonUtils.toBean(result, ResponseBean.class);
                ReturnResult returnResult =JsonUtils.toBean(responseBean.getMsgJson(), ReturnResult.class);
                if (null != returnResult && returnResult.getCode() == 0) {
                    callBack.disConnect();
                }
            }
        });
    }

    /**
     * 获取背夹电源状态
     *
     * @return 成功返回 true，失败返回 false
     */
    public boolean getPowerStatus() {
        ReturnResult returnResult = HardWareUtil.requestHardwareData("backclip_getPowerStatus");
        return returnResult != null && returnResult.getCode() == 0;
    }

    public void startDiscovery(int searchTime, final OnBluetoothDiscoverListener callback) {
        // 蓝牙搜索时间,暂时未用到.
        final BluetoothDiscoveryParam.Request param = new BluetoothDiscoveryParam.Request(searchTime);
        HardWareUtil.requestHardwareData(false, "backclip_startDiscovery", JsonUtils.toJson(param), new IHZAidlCallback.Stub() {
            @Override
            public void callback(String result) throws RemoteException {
                ResponseBean responseBean = JsonUtils.toBean(result, ResponseBean.class);
                if (null != callback) {
                    ReturnResult returnResult =JsonUtils.toBean(responseBean.getMsgJson(), ReturnResult.class);
                    if (null == returnResult || null == returnResult.getDatas() || returnResult.getDatas().isEmpty()) {
                        callback.onDiscoveryStarted();
                        callback.onDiscoveryfinished();
                        return;
                    }
                    BluetoothDiscoveryParam.Response response = JsonUtils.toBean(returnResult.getDatas().get(0), BluetoothDiscoveryParam.Response.class);
                    int methodCode = response.getCallbackMethd();
                    switch (methodCode) {
                        case BluetoothDiscoveryParam.Response.ON_BONDED_DEVICES:
                            callback.onBondedDevices(response.getPairedBluetoothDevices());
                            break;
                        case BluetoothDiscoveryParam.Response.ON_FOUND:
                            callback.onFound(response.getDevice());
                            break;
                        case BluetoothDiscoveryParam.Response.ON_DISCOVERY_STARTED:
                            callback.onDiscoveryStarted();
                            break;
                        case BluetoothDiscoveryParam.Response.ON_DISCOVERY_FINISHED:
                            callback.onDiscoveryfinished();
                            break;
                    }
                }
            }
        });
    }

    public boolean cancelDiscovery() {
        ReturnResult returnResult = HardWareUtil.requestHardwareData(false, "backclip_cancelDiscovery", "");
        return returnResult != null && returnResult.getCode() == 0;
    }

    public interface OnBluetoothDiscoverListener {
        /**
         * 已经配过对的
         *
         * @param pairedBluetoothDevices
         */
        void onBondedDevices(Set<BluetoothDevice> pairedBluetoothDevices);

        /**
         * 新发现单位
         *
         * @param newDevice
         */
        void onFound(BluetoothDevice newDevice);

        /**
         * 蓝牙搜索开始
         */
        void onDiscoveryStarted();

        /**
         * 蓝牙搜索结束
         */
        void onDiscoveryfinished();
    }


}
